package cn.wu.org.service.impl;

import cn.wu.basic.service.impl.BaseServiceImpl;
import cn.wu.org.domain.Department;
import cn.wu.org.mapper.DepartmentMapper;
import cn.wu.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    //无限级数实现
    @Override
    public List<Department> findDeptTree() {
        List<Department> allDepts = departmentMapper.findAll();

        ArrayList<Department> result = new ArrayList<>();

        //Map<Long, Department> deptMap = allDepts.stream().collect(Collectors.toMap(Department::getId, e -> e));
        Map<Long, Department> deptMap =allDepts.stream().collect(Collectors.toMap(Department::getId, e->e));
        for (Department dept : allDepts) {

            if (dept.getParentId() != null) {

                Department parent = deptMap.get(dept.getParentId());
                if (null != parent){
                    parent.getChildren().add(dept);
                }
            } else {
                result.add(dept);

            }


        }
        return result;
    }
}
